//
//  CYTransferViewController.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/7/7.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYTransferViewController.h"
#import "CYTransferHeaderView.h"
#import "CYDataSourceDelegate.h"
#import "CYTransferEnterCell.h"
#import "CYTransferCell.h"
#import "CYTransferBankCell.h"
#import "CYPayWayTableview.h"
#import "CYBankView.h"
#import "CYPickerController.h"
#import "CYSuccessTipsView.h"
@interface CYTransferViewController ()
@property (nonatomic, strong) CYTransferHeaderView *headerview;
@property (nonatomic, strong) UIButton *nextBtn;
@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) CYDataSource *datasource;
@property (nonatomic, strong) CYDelegate *delegate;
@property (nonatomic, strong) CYPayWayTableview *paywayList;/*选择转款方式的列表*/
@property (nonatomic, strong) CYView  *alphaView;/*弹出选择列表的时候，半透明背景*/
@property (nonatomic, strong) CYBankView *bankList;//银行列表
@property (nonatomic, strong) CYPickerController *dateList;//时间列表

@property (nonatomic, assign) NSUInteger currentIndex;

@property (nonatomic, strong) NSMutableArray *payeeBankArr;//收款公司的银行
@property (nonatomic, strong) NSString *payeeBankPlistName;//收款公司银行的plist名字
@property (nonatomic, strong) NSDictionary *currentPayeeBankDic;//当前选中的首款方银行信息；

@property (nonatomic, copy) NSString *name;//存款人真实姓名
@property (nonatomic, copy) NSString *time;//存款时间
@property (nonatomic, strong) NSDictionary *payWayDic;//0=网银转账 1=ATM自动提款机柜员转账 2=ATM现金入款 3=银行柜台 4=手机银行 5=其他
@property (nonatomic, strong) NSDictionary *bankDic;//存款人的银行id
@end

@implementation CYTransferViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _payeeBankPlistName = @"payeeCompanyBank.plist";
    self.nextBtn.hidden = self.headerview.hidden = NO;
    
    // Do any additional setup after loading the view.
}

- (CYTransferHeaderView *)headerview{
    if (!_headerview) {
        WS(self)
        _headerview = [[CYTransferHeaderView alloc]initWithTitles:@[@"1.选择存款银行", @"2.填写转账信息", @"3.核对转账信息"] block:^(NSUInteger index) {
            weakSelf.currentIndex = index;
        }];
        [self.view addSubview:_headerview];
        
        [_headerview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).with.offset(NAVIBAR_HEIGHT + STATUS_HEIGHT);
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, AUTO(45)));
        }];
    }
    return _headerview;
}

- (UIButton *)nextBtn{
    if (!_nextBtn) {
        _nextBtn = [[UIButton alloc]init];
        [_nextBtn addTarget:self action:@selector(actionForNextBtn) forControlEvents:UIControlEventTouchUpInside];
        _nextBtn.titleLabel.font = [UIFont systemFontOfSize:20 weight:UIFontWeightBold];
        [_nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
        [_nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_nextBtn setBackgroundColor:THEME_COLOR];
        _nextBtn.layer.masksToBounds = YES;
        _nextBtn.layer.cornerRadius = AL(5.0);
        [self.view addSubview:_nextBtn];
        
        [_nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.bottom.equalTo(self.view.mas_bottom).with.offset(-AL(PT(65)));
            make.size.mas_equalTo(CGSizeMake(AL(PT(460)), AL(PT(84))));
        }];
    }
    return _nextBtn;
}

- (UITableView *)tableview{
    if (!_tableview) {
        _tableview = [[UITableView alloc]init];
        _tableview.bounds = CGRectMake(0.0, 0.0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIBAR_HEIGHT - STATUS_HEIGHT - AUTO(45) - AL(PT(65 + 84)));
        [self.view addSubview:_tableview];
        self.alphaView.hidden = YES;
        [self setupTableview];
        
        [_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(NAVIBAR_HEIGHT + STATUS_HEIGHT + AUTO(45), 0, AL(PT(65 + 84)), 0));
        }];
    }
    return _tableview;
}


- (CYPayWayTableview *)paywayList{
    if (!_paywayList) {
        WS(self)
        _paywayList = [[CYPayWayTableview alloc]initWith:^(NSDictionary *dict) {
            [weakSelf setupPayway:dict];
        }];
        [self.view addSubview:_paywayList];
        
        [_paywayList mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_bottom).with.offset(0);
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, AL(PT(100 *5))));
        }];
    }
    
    return _paywayList;
}

- (CYBankView *)bankList{
    if (!_bankList) {
        WS(self)
        _bankList = [[CYBankView alloc]initWithData:nil block:^(NSString *bank_id, NSString *bank) {
            [weakSelf setupBank:@{bank:bank_id}];
        }];
        [self.view addSubview:_bankList];
        
        [_bankList mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_bottom).with.offset(0);
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT - NAVIBAR_HEIGHT - STATUS_HEIGHT));
        }];
    }
    return _bankList;
}

- (CYPickerController *)dateList{
    if (!_dateList) {
        WS(self)
        _dateList = [[CYPickerController alloc]initWithBlock:^(NSString *data, NSInteger type, NSString *cancelOrEnter) {
            if (type == 0)[weakSelf setupTime:(NSString *)data action:cancelOrEnter];
        }];
        [self.view addSubview:_dateList];
        
        [_dateList mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_bottom).with.offset(0);
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(_dateList.bounds.size);
        }];
    }
    return _dateList;
}

- (CYView *)alphaView{
    if (!_alphaView) {
        _alphaView = [[CYView alloc]initWithColor:[UIColor clearColor]];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(actionForSigleTap)];
        [_alphaView addGestureRecognizer:tap];
        [self.view addSubview:_alphaView];
        self.paywayList.hidden = self.bankList.hidden = self.dateList.hidden = NO;
        
        [_alphaView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(NAVIBAR_HEIGHT + STATUS_HEIGHT, 0, 0, 0));
        }];
    }
    return _alphaView;
}

- (void)setCurrentIndex:(NSUInteger)currentIndex{
    if (_currentIndex != currentIndex)
        _currentIndex = currentIndex;
    if (_currentIndex == 0 && _tableview) {
        _datasource.identifier =@"CYTransferBankCell";
        _delegate.height = AUTO(80);
        _datasource.dataArr = _payeeBankArr;
        _tableview.scrollEnabled = (_payeeBankArr.count * AL(PT(160)) > _tableview.bounds.size.height)?YES:NO;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableview reloadData];
    }
    else if (_currentIndex == 1){
        _datasource.identifier =@"CYTransferCell";
        _datasource.dataArr = (NSMutableArray *)[self getTitle:0];
        _delegate.height = AUTO(45);
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.scrollEnabled = NO;
        [_tableview reloadData];
    }
    else if (_currentIndex == 2){
        _datasource.identifier =@"CYTransferEnterCell";
        _datasource.dataArr = (NSMutableArray *)[self getTitle:1];
        _delegate.height = 45;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.scrollEnabled = NO;
        [_tableview reloadData];
    }
    if (_currentIndex < 2)
        [self.nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    else
        [self.nextBtn setTitle:@"完成" forState:UIControlStateNormal];
    
}

//收款公司的银行
- (void)setPayeeBankArr:(NSMutableArray *)payeeBankArr{
    if (!payeeBankArr)
        _payeeBankArr = [CYCache getCache:_payeeBankPlistName];
    else if (_payeeBankArr != payeeBankArr){
        _payeeBankArr = payeeBankArr;
        [CYCache cache:_payeeBankArr plist:_payeeBankPlistName];
    }
    if (!_tableview)
        self.tableview.hidden = NO;//如果tableview没有初始化，则初始化
    _datasource.dataArr = _payeeBankArr;
    [_tableview reloadData];
    
}

- (void)setupTableview{
    WS(self)
    _delegate = [[CYDelegate alloc]initWithCellHeight:AUTO(80) views:nil block:^(NSIndexPath *index) {
        [weakSelf selectCell:index];
    }];
    
    _datasource = [[CYDataSource alloc]initWithData:_payeeBankArr identifier:@"CYTransferBankCell" block:^(id cell, id data) {
        [weakSelf bind:cell data:data];
    }];
    _delegate.deselect = NO;
    _tableview.delegate = _delegate;
    _tableview.dataSource = _datasource;
    _tableview.scrollEnabled = (_payeeBankArr.count * AUTO(80) > _tableview.bounds.size.height)?YES:NO;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
}



- (void)selectCell:(NSIndexPath *)index{
    if ([_datasource.identifier isEqualToString:@"CYTransferBankCell"])
        _currentPayeeBankDic = _payeeBankArr[index.row];
}

- (void)bind:(id)cell data:(NSDictionary *)dict{
    WS(self)
    if (self.currentIndex == 0) {
        CYTransferBankCell *new_cell = (CYTransferBankCell *)cell;
        new_cell.bankName = dict[@"name"];//银行名称
        new_cell.address = dict[@"childen_name"];//银行地址
        new_cell.account = dict[@"number"];//银行账号
        new_cell.name = dict[@"user"];//户主名称
        [CYHttps loadingWithFile:dict[@"bank_api_img_url"] complete:^(id data) {
            new_cell.bankLogo = data;//银行logo
        }];
    }
    else if (self.currentIndex == 1){
        CYTransferCell *new_cell =  (CYTransferCell *)cell;
        new_cell.title = dict[@"title"];
        new_cell.textField.placeholder = dict[@"placeholedr"];
        new_cell.style = dict[@"style"];
        if ([dict[@"title"] isEqualToString:@"存款金额"])
            new_cell.textField.text = _money;
        new_cell.mylist = ^(NSString *title) {
            [self.view endEditing:YES];
            if ([title isEqualToString:@"存款方式"])
                [weakSelf showPayWayList];
            else if ([title isEqualToString:@"使用银行"])
                [weakSelf showBankList];
            else if ([title isEqualToString:@"存款时间"])
                [weakSelf showDateList];
        };
        new_cell.myblock = ^(id data) {
            if ([dict[@"title"] isEqualToString:@"姓名"])
                _name = data;
            else if ([dict[@"title"] isEqualToString:@"使用银行"])
                _bankDic = data;
            else if ([dict[@"title"] isEqualToString:@"存款方式"])
                _payWayDic = data;
            else if ([dict[@"title"] isEqualToString:@"存款时间"])
                _time = data;
             else if ([dict[@"title"] isEqualToString:@"存款金额"])
                 _money = data;
            //保存输入的文字信息，传给服务器
        };
    }
    else if (self.currentIndex == 2){
        CYTransferEnterCell *new_cell =  (CYTransferEnterCell *)cell;
        NSString *content;
        if ([[[dict allValues] firstObject] isKindOfClass:[NSString class]])
            content = [[dict allValues] firstObject];
        else{
            NSDictionary *new_dict = [[dict allValues] firstObject];
            content = [[new_dict allKeys] firstObject];
        }
        new_cell.title = [[dict allKeys] firstObject];
        new_cell.content = content;
    }
    
}

//弹出转账方式列表
- (void)showPayWayList{
    _alphaView.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        _paywayList.transform = CGAffineTransformMakeTranslation(0, -AL(PT(100 * 5)));
    }];
}

//弹出选择银行列表
- (void)showBankList{
    
    [UIView animateWithDuration:0.3 animations:^{
        _bankList.transform = CGAffineTransformMakeTranslation(0, -_bankList.bounds.size.height);
    }];
}

//弹出时间选择器
- (void)showDateList{
    _alphaView.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        _dateList.transform = CGAffineTransformMakeTranslation(0, - AL(PT(460)));
    }];
}

//设置存款方式
- (void)setupPayway:(NSDictionary *)dict{
    _alphaView.hidden = YES;
    CYTransferCell *cell = [_tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];//存款方式的坐标固定
    cell.dict = dict;  //选中列表的文字，把它赋值给存款方式
    
}
//设置使用银行的名称
- (void)setupBank:(NSDictionary *)dict{
    _alphaView.hidden = YES;
    CYTransferCell *cell = [_tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];//银行名称的坐标固定
    cell.dict = dict;
}

//设置存款时间
- (void)setupTime:(NSString *)time action:(NSString *)cancelOrEnter{
    if (cancelOrEnter)
        _alphaView.hidden = YES;
    CYTransferCell *cell = [_tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:0]];//存款时间的坐标固定
    cell.text = [NSString insertYearWithDateString:time];//转换成带年的时间
}

//下一步
- (void)actionForNextBtn{
    [self.view endEditing:YES];
    if (_headerview.currentIndex == 0) {
        if (!_currentPayeeBankDic || ![_tableview indexPathForSelectedRow]) {//收款方银行信息为空
            [CYHUD show:@"请选择正确的银行"];
            return;
        }
        _headerview.currentIndex += 1;
    }
    else if (_headerview.currentIndex == 1){
        if (!_name){
            [CYHUD show:@"请填写姓名"];
            return;
        }else if ([_payWayDic allValues].count == 0){
            [CYHUD show:@"请选择存款方式"];
            return;
        }else if ([_bankDic allValues].count == 0){
            [CYHUD show:@"请选择转账银行"];
            return;
        }else if (!_money){
            [CYHUD show:@"请填写转账金额"];
            return;
        }else if (!_time){
            [CYHUD show:@"请选择存款时间"];
            return;
        }
        _headerview.currentIndex += 1;
    }
    else if (_headerview.currentIndex == 2)
        [self transferHttps];
}

//半透明背景单击触摸手势响应方法
- (void)actionForSigleTap{
    [UIView animateWithDuration:0.3 animations:^{
        _paywayList.transform = CGAffineTransformIdentity;
        _dateList.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        _alphaView.hidden = YES;
    }];
}

//转账申请成功
- (void)actionForTransferSuccess{
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSArray *)getTitle:(NSUInteger)index{
    
  NSString *moneyLBL_placeholedr = [NSString stringWithFormat:@"范围%d~%d",[_currentPayeeBankDic[@"min_quota"] intValue],[_currentPayeeBankDic[@"max_quota"] intValue]];
    if (index == 0)
        return @[@{@"title":@"姓名",@"placeholedr":@"输入持卡人人姓名",@"style":@"input"},@{@"title":@"存款方式",@"placeholedr":@"选择存款方式",@"style":@"selection"},
                 @{@"title":@"使用银行",@"placeholedr":@"选择银行",@"style":@"selection"}, @{@"title":@"存款金额",@"placeholedr":moneyLBL_placeholedr,@"style":@"input"},
                 @{@"title":@"存款时间",@"placeholedr":@"选择日期",@"style":@"selection"}];
    else
        return @[@{@"姓名":(_name)?_name:@""},@{@"存款金额":(_money)?_money:@""},
                 @{@"存入银行":(_currentPayeeBankDic[@"name"])?_currentPayeeBankDic[@"name"]:@""},
                 @{@"存款方式":(_payWayDic)?_payWayDic:@""},@{@"存款时间":(_time)?_time:@""},
                 @{@"您使用的银行":(_bankDic)?_bankDic:@""}];
}

//收款公司的银行
- (void)https{
    
    NSDictionary *para = @{@"username":[CYCache readDataWithKey:@"username"],
                           @"token":[CYCache readDataWithKey:@"token"]};
    
    self.task = [CYHttps POST:API_payeeBankList parameters:para showHUD:NO progress:nil success:^(id data) {
        DeLog(@"data %@",data);
        if (data)
            self.payeeBankArr = data;//收款公司的银行
        else
            self.payeeBankArr = nil;
    } failure:^(id string) {
        self.payeeBankArr = nil;
    }];
    
}

//请求卡转卡
- (void)transferHttps{
    NSDictionary *para = @{@"payee_id":_currentPayeeBankDic[@"id"],//公司银行id
                           @"payee_number":_currentPayeeBankDic[@"number"],//公司银行卡号
                           @"payee_name":_currentPayeeBankDic[@"name"],//公司银行卡开户人姓名
                           @"bank_id":[[_bankDic allValues] firstObject],//自己银行id
                           @"depositor_name":_name,//存款人姓名
                           @"depositor_mode":[[_payWayDic allValues] firstObject],//存款方式
                           @"amount":[_money stringByReplacingOccurrencesOfString:@"," withString:@""],//存款人金额
                           @"depositor_time":_time,//存款时间
                           @"username":[CYCache readDataWithKey:@"username"],//用户名
                           @"token":[CYCache readDataWithKey:@"token"]};//token
    
    
    self.spareTask = [CYHttps POST:API_transfer parameters:para showHUD:YES progress:nil success:^(id data) {
        if (data)
            [CYSuccessTipsView showTitle:@"转账申请成功!" buttonTitle:@"确定" block:^{
                [self actionForTransferSuccess];
            }];
    } failure:nil];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self https];
}


- (void)setupNavigationBarTintColor:(UIColor *)color{
    [super setupNavigationBarTintColor:color];
    self.navigationItem.title = @"银行转账";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
